import { computed, ref } from 'vue'
import { useTheme } from '@/composables/theme/theme'
import { useUserStore } from '@/stores/user'
import type { FunctionItem } from '@/stores/user'
import { UserAPI } from '@/api'
// 从 userStore 获取用户信息
const userStore = useUserStore()

// 从 userStore 获取计数信息
export const countInfo = computed(() => {
  const setting = userStore.userSetting
  return {
    remind: setting?.remindCount || 0,
    account: setting?.accountCount || 0,
    memo: setting?.memoCount || 0,
  }
})

export const userInfo = computed(() => {
  if (!userStore.userInfo) {
    // 如果没有用户信息，返回默认值
    return {
      id: '0',
      username: 'none',
      avatar: 'https://img.zwfcyy.top/echo-app/logo/er-main.png',
      realname: '未登录',
      telephone: '',
      email: '',
      status: 0,
      delFlag: 0,
      createTime: '',
      departIds: '',
      relTenantIds: '',
      clientId: '',
    }
  }
  return userStore.userInfo
})

// 从 userStore 获取设置功能列表数据
export const allSettingList = computed<FunctionItem[]>(() => {
  const permissions = userStore.permissions
  if (!permissions?.Setting || !Array.isArray(permissions.Setting) || permissions.Setting.length === 0) {
    // 如果没有权限数据，只显示"退出登录"
    return [{
      path: '/logout',
      name: '退出登录',
      icon: 'https://img.zwfcyy.top/echo-app/icon/function/logout-w.svg',
      id: '1922091572445495298',
      sort: 10,
      class: 'bg-gray',
      collect: false,
      desc: null,
      count: 0,
    }]
  }
  // 将权限数据转换为 FunctionItem 类型
  return permissions.Setting.map((item) => {
    if (typeof item === 'string') {
      return {
        path: item,
        name: item,
        icon: '',
        id: item,
        sort: 0,
        collect: false,
        count: 0,
        class: 'bg-gray',
        desc: null,
      }
    }
    return item as FunctionItem
  })
})

// 功能类型数据 - 从全部设置项中筛选出 collect 为 true 的项目
export const functionTypes = computed(() => {
  const settingList = allSettingList.value || []
  return settingList
    .filter(item => item.collect)
    .sort((a, b) => a.sort - b.sort)
    .map(item => ({
      name: item.name,
      icon: item.icon,
      path: item.path,
      count: item.count,
    }))
})

// 服务菜单数据
export const allServices = computed(() => {
  const settingList = allSettingList.value || []
  return settingList
    .filter(item => !item.collect)
    .sort((a, b) => a.sort - b.sort)
    .map(item => ({
      name: item.name,
      icon: item.icon,
      path: item.path,
      class: item.class || 'bg-gray',
      desc: item.desc || undefined,
    }))
})
// Composable函数
export function useSettingPage() {
  const remindType = computed(() => userStore.userSetting?.remindType || '0')

  const showActionSheet = ref(false)

  const actions = computed(() => [
    { name: '暂停通知', value: 0, color: remindType.value === '0' ? '#0083ff' : '' },
    { name: '手机短信', value: 1, color: remindType.value === '1' ? '#0083ff' : '' },
    { name: '邮箱通知', value: 2, color: remindType.value === '2' ? '#0083ff' : '' },
  ])

  const { toggleTheme } = useTheme()

  // 导航方法
  const navigateTo = (path: string) => {
    console.log('导航到:', path)

    // 如果是/logout 执行退出登录，并关闭所有页面跳转pages/index/index
    if (path === '/logout') {
      // 执行退出登录操作
      userStore.logout().then(() => {
        // 关闭所有页面并跳转到首页
        uni.reLaunch({
          url: '/pages/index/index',
        })
      })
    }
    else if (path === '/remindMode') {
      showActionSheet.value = true
    }
    else if (path === '/feedback') {
      // 打开微信小程序的反馈与投诉
      uni.openCustomerServiceChat({
        extInfo: {
          url: 'https://work.weixin.qq.com/kfid/kfc123456789',
        },
        corpId: 'your_corp_id', // 需要替换为实际的企业ID
        success: () => {
          console.log('打开客服会话成功')
        },
        fail: (err) => {
          console.error('打开客服会话失败:', err)
          // 如果打开失败，可以显示提示信息
          uni.showToast({
            title: '打开反馈功能失败',
            icon: 'none',
          })
        },
      })
    }
    else {
      uni.navigateTo({ url: path })
    }
  }

  const switchTab = (path: string) => {
    uni.switchTab({ url: path })
  }

  // 显示二维码方法
  const showQRCode = () => {
    // 显示二维码的逻辑
    console.log('显示二维码')
  }

  // 切换主题方法
  const handleThemeToggle = () => {
    toggleTheme()
  }

  // 隐藏actionsheet
  const handleClose = () => {
    showActionSheet.value = false
  }

  // 处理选择
  const handleSelect = async (payload: any) => {
    console.log('handleSelect payload:', payload)
    let value
    if (payload?.item && typeof payload.item.value !== 'undefined') {
      value = payload.item.value
    }
    else if (payload?.action && typeof payload.action.value !== 'undefined') {
      value = payload.action.value
    }
    else if (typeof payload.value !== 'undefined') {
      value = payload.value
    }
    else if (Array.isArray(payload) && payload[0] && typeof payload[0].value !== 'undefined') {
      value = payload[0].value
    }
    if (typeof value === 'undefined') {
      uni.showToast({ title: '请选择一个通知方式', icon: 'none' })
      return
    }
    const params = {
      field: 'remindType',
      value: value.toString(),
    }
    try {
      const result = await UserAPI.updateUserInfo(params)
      console.log('更新成功:', result)

      // 更新用户信息中的设置
      if (userStore.userInfo && userStore.userSetting) {
        userStore.userSetting.remindType = value.toString()
      }

      uni.showToast({ title: '设置成功', icon: 'success' })
    }
    catch (error) {
      console.error('更新失败:', error)
      uni.showToast({ title: '设置失败', icon: 'error' })
    }
    showActionSheet.value = false
  }

  return {
    actions,
    showActionSheet,
    userInfo,
    countInfo,
    functionTypes,
    allServices,
    navigateTo,
    switchTab,
    showQRCode,
    handleClose,
    handleSelect,
    handleThemeToggle,
  }
}
